package com.ambow.servlet;

import java.io.IOException;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ambow.Entity.*;
import com.ambow.service.CellService;
import com.ambow.service.StockMoveService;
import com.ambow.service.StockService;
import com.ambow.service.TextBookService;
import com.ambow.service.impl.CellServiceImpl;
import com.ambow.service.impl.StockMoveServiceImpl;
import com.ambow.service.impl.StockServiceImpl;
import com.ambow.service.impl.TextBookServiceImpl;


/// pages/module/storage/storage005/storage_move.jsp?
@WebServlet("/StockMoveServlet")//查询移库存在问题，根据书架和书名进行判断。一致改变数量。不一致就增加。还有js验证有问题
public class StockMoveServlet extends HttpServlet {

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	StockService stockService = new StockServiceImpl();
	CellService cellService = new CellServiceImpl();
	TextBookService textBookService = new TextBookServiceImpl();
	StockMoveService stockMoveService = new StockMoveServiceImpl();
 
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stubt
        
		String status = request.getParameter("status");
		System.out.println("status::::"+status);
	 
       
		if (status.equals("query")) {
			query(request, response);

		} else if (status.equals("modify")) {
			modify(request, response);

		} else if (status.equals("move")) {// 加入移库记录

			move(request, response);

		} else if (status.equals("validat")) {// js 验证
			validat(request, response);
		}else if(status.equals("a")){
		a(request,response); 
		}
		else {
			System.out.println("0000000");
		}
	}

	/**
	 *<p>Title: a</p>  
	 *<p>Description: </p>
	 * @param
	 * @return
	 * @param request
	 * @param response
	 */
	private void a(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text"); 
	    PrintWriter out;
		try {
			out = response.getWriter();
			 String   username = request.getParameter("username");  
		        System.out.println(username);   
		        out.write(username+"222");  
		      //  request.getRequestDispatcher("pages/a.jsp").forward(request, response);  
		        out.flush();  
		        out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	// 记录移库记录，如果接收架位上存在该书，只需改变数量。同时，所移架位的数量减少
	private void move(HttpServletRequest request, HttpServletResponse response) {
		boolean f1=false,f2=false,f3=false;
		String cellFrom=request.getParameter("cellName");//原架位
		String textBookName=request.getParameter("textBookName");
		String [] from= {cellFrom,textBookName};
		 Stock stockFrom=stockService.QueryOne("from Stock stock where stock.cell.name=? and stock.textBook.name=?", from);
			int amount = Integer.valueOf(request.getParameter("amount"));// 原架位数量（已在页面修改，这是移库后的数量）
			stockFrom.setAmount(amount);
			System.out.println("safdhgjjjhjjjjjjjjjjjjj"+amount);
			 f1=stockService.update(stockFrom);
		 
		 
		 Stock stockTo=new Stock();
		String cellNameto = request.getParameter("cellNameto");// 现架位名称
		int toAmount = Integer.valueOf(request.getParameter("toAmount"));// 接收的数量
		String[] param= {cellNameto};
		stockTo.setCell(cellService.queryOne("from Cell cell where cell.name=?",param));
		stockTo.setTextBook(stockFrom.getTextBook());
		stockTo.setAmount(toAmount);
		List<Stock> list=stockService.Query("from Stock", null);
		for (Stock stock : list) {
			if((stock.getTextBook().getId()==stockTo.getTextBook().getId())&&(stock.getCell().getId()==stockTo.getCell().getId())) {
				stock.setAmount(stock.getAmount()+stockTo.getAmount());
				f2=stockService.update(stock); break;
		 }
			 
		 }
		if(f2==false) f2=stockService.add(stockTo);
	
		
			StockMove stockMove = new StockMove();
			stockMove.setAmount(toAmount);
			stockMove.setFromCell(stockFrom.getCell());
			stockMove.setToCell(stockTo.getCell());
			stockMove.setMoveDate(new Date());
			stockMove.setRemark("无");
			stockMove.setOperator(null);// 注 ？？？意添加管理员
			 f3 = stockMoveService.SaveSingle(stockMove);
			if (f1&f2&f3) {
				try {
					request.getRequestDispatcher("pages/module/storage/storage005/storage_move_query.jsp").forward(request,
							response);
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		

	

	private void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String shelf = request.getParameter("shelf");// 架位号
		String bookName = request.getParameter("bookName");// 教材名称
		System.out.println("shelf:" + shelf);
		System.out.println("bookName:" + bookName);
		if (shelf == "" && bookName == "") {// 为空
			List<Stock> list = stockService.Query("from Stock", null);
			System.out.println("stocnullzhi:" + list.size());
			request.setAttribute("list", list);
		} else if (shelf != "" && bookName == "") {
			String[] param = { shelf };
			List<Stock> list = stockService.Query("from Stock as stock where stock.cell.name=?", param);
			System.out.println("stocshelfzhi:" + list.size());
			request.setAttribute("list", list);

		} else if (shelf == "" && bookName != "") {
			String[] param = { "%" + bookName + "%" };
			List<Stock> list = stockService.Query("from Stock as stock where stock.textBook.name like ?", param);
			System.out.println("stockbooknamezhi:" + list.size());
			request.setAttribute("list", list);
		} else if (shelf != "" && bookName != "") {
			String[] param = { shelf, "%" + bookName + "%" };
			List<Stock> list = stockService
					.Query("from Stock as stock where stock.cell.name=? and stock.textBook.name like ? ", param);
			System.out.println("stocksbzhi:" + list.size());
			request.setAttribute("list", list);
		}

		request.getRequestDispatcher("pages/module/storage/storage005/storage_move_query.jsp").forward(request,
				response);

	}

	// 将单选框选择的值保存，然后请求转发给移库页面中
	private void modify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Integer id = Integer.valueOf(request.getParameter("radio"));
		List<Stock> list = new ArrayList<Stock>();
		Stock stock = stockService.getOne(Stock.class, id);

		request.setAttribute("stock", stock);

		request.getRequestDispatcher("pages/module/storage/storage005/storage_move.jsp").forward(request, response);

	}

	// 验证 输入的书架名是否存在于数据库中 js ajax
	private void validat(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		response.setContentType("text"); 
		String cellNameto = request.getParameter("cellNameto");// 取得名称
		System.out.println("cellnameto    ajax:::::" + cellNameto);
		String[] param = { cellNameto };
		Cell stockTo = cellService.queryOne("from Cell as cell where cell.name=?", param);
		String data=null;
	    PrintWriter out;
		try {
			out = response.getWriter();
			if(stockTo==null) {
				data="false";
			}else {
				data="true";
			}
		 
			
		       
		        out.write(data);   
		        out.flush();  
		        out.close();
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	
			

	}

}
